package com.tticar.invmanager.controller;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.tticar.invmanager.common.exception.MyServiceException;
import com.tticar.invmanager.common.utils.MyResponseBody;
import com.tticar.invmanager.common.utils.date.DateStyle;
import com.tticar.invmanager.common.utils.date.DateUtil;
import com.tticar.invmanager.entity.*;
import com.tticar.invmanager.entity.vo.MyPage;
import com.tticar.invmanager.entity.vo.PurchaseAddDto;
import com.tticar.invmanager.entity.vo.PurchaseGoodsDto;
import com.tticar.invmanager.service.IMSalesService;
import com.tticar.invmanager.service.ISaleReturnService;
import com.tticar.invmanager.service.ISysUserService;
import com.tticar.invmanager.service.IWRelativeUnitService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 销售退货表 前端控制器
 * </p>
 *
 * @author joeyYan
 * @since 2019-01-04
 */
@Controller
@RequestMapping("/saleReturn")
public class SaleReturnController extends BaseController {

    @Autowired
    private ISaleReturnService saleReturnService;
    @Autowired
    private IWRelativeUnitService relativeUnitService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private IMSalesService salesService;

    @PostMapping
    @ResponseBody
    public MyResponseBody post(SaleReturn saleReturn) {
        saleReturnService.insertOrUpdate(saleReturn);
        return MyResponseBody.success();
    }

    @PostMapping("delete")
    @ResponseBody
    public MyResponseBody delete(@RequestParam("codes[]") List<String> codes) {
        MyResponseBody responseBody = MyResponseBody.success();
        Wrapper wrapper = new EntityWrapper<>();
        wrapper.eq("code", codes.get(0));
        List<SaleReturn> saleReturns = saleReturnService.selectList(wrapper);
        List<Long> ids = new ArrayList<>();
        for (SaleReturn entity : saleReturns) {
            ids.add(entity.getId());
        }
        saleReturnService.delete(ids);
        Wrapper wrapper1 = new EntityWrapper<>();
        wrapper1.eq("return_order", codes.get(0));
        MSales mSales = salesService.selectOne(wrapper1);
        if (mSales != null) {
            mSales.setOrderStatus(1);
            mSales.setReturnOrder(null);
            salesService.updateById(mSales);
        }

        return responseBody;
    }

    @GetMapping("{id}")
    @ResponseBody
    public MyResponseBody get(@PathVariable("id") Long id) {
        MyResponseBody responseBody = MyResponseBody.success();
        responseBody.setData(saleReturnService.selectById(id));
        return responseBody;
    }

    @GetMapping("edit")
    public String edit(SaleReturn saleReturn, ModelMap modelMap) {
        modelMap.put("id", saleReturn.getId());
        return "/saleReturn/saleReturn_edit";
    }

    @GetMapping("list")
    @ResponseBody
    public Page list(SaleReturn saleReturn, MyPage<SaleReturn> page) {
        return saleReturnService.selectPage(saleReturn, page);
    }

    @GetMapping
    public String index(String searchText,ModelMap modelMap) {
        modelMap.put("searchText", searchText);
        return "/saleReturn/saleReturn";
    }

    @GetMapping("detailGoodsList")
    @ResponseBody
    public List<Map> detailList(String code) {
        if (StringUtils.isBlank(code)) {
            return null;
        }
        List<Map> purchaseDetailList = this.saleReturnService.detailGoodsList(code);
        return purchaseDetailList;
    }

    @GetMapping("detailPage")
    public String detailPage(@RequestParam("saleReturnCode") String saleReturnCode,ModelMap modelMap) {
        modelMap.put("purchaseId", saleReturnCode);
        Wrapper w = new EntityWrapper<>();
        w.eq("code", saleReturnCode);
        List<SaleReturn> saleReturns = saleReturnService.selectList(w);
        BigDecimal totalMoney = BigDecimal.ZERO;
        for (SaleReturn dto : saleReturns) {
            totalMoney = totalMoney.add(dto.getUnitPrice().multiply(new BigDecimal(dto.getCount())));
        }
        SaleReturn saleReturn = saleReturns.get(0);
        Wrapper wrapper = new EntityWrapper<>();
        wrapper.eq("id", saleReturn.getCustomId());
        WRelativeUnit wRelativeUnit = relativeUnitService.selectOne(wrapper);
        if (wRelativeUnit != null) {
            modelMap.put("relative", wRelativeUnit.getName());
        }
        Wrapper wrapper1 = new EntityWrapper<>();
        wrapper1.eq("username", saleReturn.getUsername());
        SysUser sysUser = userService.selectOne(wrapper1);
        if (sysUser != null) {
            modelMap.put("username", sysUser.getNickname());
        }
        modelMap.put("purchase", saleReturn);
        if (saleReturn.getPayStatus() == 0 && saleReturn.getRepositoryStatus() == 1) {
            modelMap.put("otherMoney", 1);
        } else {
            modelMap.put("otherMoney", 0);
        }

        if (saleReturn.getPayStatus() == 1) {
            modelMap.put("payStatus", "已结清");
        } else {
            modelMap.put("payStatus", "未结清");
        }
        if (saleReturn.getRepositoryStatus() == 0) {
            modelMap.put("orderStatus", "未出库");
        } else if (saleReturn.getRepositoryStatus() == 1) {
            modelMap.put("orderStatus", "已出库");
        }

        if (saleReturn.getPayStatus() == 0 && saleReturn.getRepositoryStatus() == 1) {
            modelMap.put("moneyMessage", 1);
        }
        modelMap.put("ptime", DateUtil.DateToString(saleReturn.getOrderTime(), DateStyle.YYYY_MM_DD));
        modelMap.put("ctime", DateUtil.DateToString(saleReturn.getCtime(), DateStyle.YYYY_MM_DD_HH_MM_SS));

        modelMap.put("totalMoney", totalMoney.toString());
        modelMap.put("hasPay", saleReturn.getRealPay().toString());
        modelMap.put("needPay", saleReturn.getNeedPay() == null ? "0" : saleReturn.getNeedPay().toString());
        return "/saleReturn/new/saleReturnDetailWindow";
    }

    @PostMapping("detailList")
    @ResponseBody
    public List<Map> detailListByDetail(String saleReturnCode) {
        List<Map> saleDetailList = this.saleReturnService.getSaleDetailList(saleReturnCode);

        return saleDetailList;
    }

    /**
     * 销售退货入库
     * */
    @PostMapping("inRepositoryFromWindow")
    @ResponseBody
    public MyResponseBody inRepositoryFromWindow(String saleReturnCode,String rows,BigDecimal realPay,BigDecimal totalMoney,
                                                 Integer payStatus,String remark) {
        MyResponseBody responseBody = MyResponseBody.success();
        List<PurchaseGoodsDto> goodsList = JSONArray.parseArray(rows, PurchaseGoodsDto.class);

        saleReturnService.inRepositoryForSaleReturn(saleReturnCode,goodsList,realPay,totalMoney,payStatus,remark);
        return responseBody;
    }

    /**
     * 结算
     * */
    @PostMapping("endCountSaleReturn")
    @ResponseBody
    public MyResponseBody endCountSaleReturn(String saleReturnCode,BigDecimal realPay,BigDecimal totalMoney,
                                                 Integer payStatus,String remark) {
        MyResponseBody responseBody = MyResponseBody.success();
        saleReturnService.endCountSaleReturn(saleReturnCode,realPay,totalMoney,payStatus,remark);
        return responseBody;
    }

    /**
     * 撤销入库
     * */
    @PostMapping("cancelInForSaleReturn")
    @ResponseBody
    public MyResponseBody cancelInForSaleReturn(String saleReturnCode) {
        MyResponseBody responseBody = MyResponseBody.success();
        saleReturnService.cancelInForSaleReturn(saleReturnCode);
        return responseBody;
    }

    /**
     * 撤销结算
     * */
    @PostMapping("cancelEndCount")
    @ResponseBody
    public MyResponseBody cancelEndCount(String saleReturnCode) {
        MyResponseBody responseBody = MyResponseBody.success();
        saleReturnService.cancelEndCount(saleReturnCode);
        return responseBody;
    }

    /**
     * 新增跳转页
     * */
    @RequestMapping("addSaleReturn")
    public String addSaleReturn(HttpServletRequest request, ModelMap modelMap) {
        long timeToken = System.currentTimeMillis();
        modelMap.put("addSaleReturnToken", String.valueOf(timeToken));
        request.getSession().setAttribute("saleReturnToken",String.valueOf(timeToken));
        return "/saleReturn/saleReturnAdd";
    }

    /**
     * 新增销售退货
     * */
    @PostMapping(value = "addRecord", produces="application/json;charset=UTF-8")
    @ResponseBody
    public MyResponseBody addRecord(PurchaseAddDto dto, String goods) throws ParseException {
        if (request.getSession().getAttribute("saleReturnToken") == null ||
                !request.getSession().getAttribute("saleReturnToken").toString().equals(dto.getToken())) {
            throw new MyServiceException("提交已受理，请勿重复提交");
        }
        request.getSession().removeAttribute("saleReturnToken");
        MyResponseBody responseBody = MyResponseBody.success();
        List<PurchaseGoodsDto> goodsList = JSONArray.parseArray(goods, PurchaseGoodsDto.class);
        dto.setGoodsList(goodsList);
        saleReturnService.addSaleReturn(dto);
        return responseBody;
    }

    /**
     * 整单退货
     * */
    @PostMapping("allReturn")
    @ResponseBody
    public MyResponseBody allReturnForSale(@RequestParam("id[]") List<Long> ids) {
        MyResponseBody responseBody = MyResponseBody.success();
        Long saleId = ids.get(0);
        String allReturnCode = saleReturnService.allReturnForSale(saleId);
        responseBody.setData(allReturnCode);
        return responseBody;
    }
}
